package com.dabai.qrtools.ui;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.method.DigitsKeyListener;
import android.text.method.ScrollingMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.dabai.qrtools.R;
import com.dabai.qrtools.data.Patterns;
import com.dabai.qrtools.dialog.MdcDialog;
import com.dabai.qrtools.other.ContactUtils;
import com.dabai.qrtools.other.LinkUtils;
import com.dabai.qrtools.other.MainUtils;
import com.dabai.qrtools.other.WifiUtils;
import com.dabai.qrtools.utils.AESUtils;
import com.dabai.qrtools.utils.Base64;
import com.dabai.qrtools.utils.DabaiUtils;
import com.dabai.qrtools.utils.ShareUtils;
import com.dabai.qrtools.utils.StringUtils;
import com.dabai.qrtools.utils.ThemeUtils;
import com.dabai.qrtools.utils.ViewUtils;
import com.dabai.qrtools.utils.WifiAdmin;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.chip.Chip;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;
import java.util.Objects;
import java.util.regex.Matcher;

public class ResultActivity extends AppCompatActivity {

    private Context context;
    private MaterialToolbar mToolbar;
    private TextView mResulttext;
    private String result;

    private Chip mChipgroup1chip1;
    private Chip mChipgroup1chip2;
    private Chip mChipgroup1chip3;
    private Chip mChipgroup1chip4;
    private Chip mChipgroup1chip5;

    private Chip mChipgroup2chip1;
    private Chip mChipgroup2chip2;
    private Chip mChipgroup2chip3;
    private Chip mChipgroup2chip4;

    private Chip mChipgroup3chip1;
    private Chip mChipgroup3chip2;
    private Chip mChipgroup3chip3;

    private Chip mChipgroup4chip1;
    private Chip mChipgroup4chip2;
    private Chip mChipgroup4chip3;
    private Chip mChipgroup4chip4;
    private CardView mChipgroup3;
    private CardView mChipgroup4;

    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        initViews();

        context = this;

        ThemeUtils.setAutoUiModeStatusBar(this, this);
        setSupportActionBar(mToolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        //数据库创建与初始化
        db = openOrCreateDatabase("HistoricalRecord", Context.MODE_PRIVATE, null);
        String create = "create table if not exists ScanHistory(id integer primary key autoincrement,content text not null unique);";
        db.execSQL(create);

        Intent intent = getIntent();

        result = intent.getStringExtra("result");

        if (result == null) {
            DabaiUtils.showToast(context, "结果为空，无法显示");
            finish();
            return;
        }

        mResulttext.setText(result);

        checkContent();
        initListenerEvent();

        ContentValues in = new ContentValues();
        in.put("content", result);
        db.insert("ScanHistory", null, in);

    }


    /**
     * 检查内容
     */
    private void checkContent() {
        if (result.startsWith("ssr://") && result.length() > 100) {
            mChipgroup2chip4.setVisibility(View.VISIBLE);
        }

        if (StringUtils.containsIgnoreCase(result, "BEGIN")) {
            mChipgroup4.setVisibility(View.VISIBLE);
        }

        if (StringUtils.containsIgnoreCase(result, "S:") && StringUtils.containsIgnoreCase(result, "T:")) {
            // 自动连接wifi
            mChipgroup3.setVisibility(View.VISIBLE);
        }

    }

    private void initListenerEvent() {

        mChipgroup1chip1.setOnClickListener(v -> {
            DabaiUtils.copyText(context, result);
        });
        mChipgroup1chip2.setOnClickListener(v -> {

            MainUtils.toFreeCopy(context, result);

        });
        mChipgroup1chip3.setOnClickListener(v -> {
            ShareUtils.shareText(context, result);
        });
        mChipgroup1chip4.setOnClickListener(v -> {
            MdcDialog.copyDialog(context, "base64解码结果", Base64.decode(result))
                    .getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
        });

        mChipgroup1chip5.setOnClickListener(v -> {

            MdcDialog.showInputDialog(context, "AES解密", "", "请输入密码"
                    , new MdcDialog.OnInputDialogButtonListener() {
                        @Override
                        public void confirm(DialogInterface dialog, String content) {
                            if (!content.isEmpty()) {
                                dialog.dismiss();
                                MdcDialog.copyDialog(context, "AES解密结果", AESUtils.decrypt(result, content))
                                        .getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
                            }
                        }

                        @Override
                        public void start(DialogInterface dialog, TextInputLayout textInputLayout) {
                            textInputLayout.getEditText().setFilters(new InputFilter[]{
                                    //只能输入字母和数字
                                    DigitsKeyListener.getInstance("1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM")});
                        }

                        @Override
                        public void cancel() {
                        }
                    }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);


        });


        mChipgroup2chip1.setOnClickListener(v -> {
            DabaiUtils.openLink(context, result);
        });

        mChipgroup2chip2.setOnClickListener(v -> {
            DabaiUtils.openLinkWithBrowserActivity(context, result);
        });

        mChipgroup2chip3.setOnClickListener(v -> {

            Matcher matcher = Patterns.WEB_URL.matcher(result);
            ArrayList<String> links = new ArrayList<>();
            while (matcher.find()) {
                String link = matcher.group();
                links.add(link);
            }
            if (links.isEmpty()) {
                DabaiUtils.showToast(context, "无链接");
            } else {
                String[] items = links.toArray(new String[0]);
                new MaterialAlertDialogBuilder(context)
                        .setTitle("提取链接")
                        .setItems(items, (dialog, which) -> {
                            LinkUtils.useLinkDialog(context, items[which]);
                        }).show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
            }

        });

        mChipgroup2chip4.setOnClickListener(v -> {
            LinkUtils.useSsrLink(context, result);
        });

        mChipgroup4chip1.setOnClickListener(v -> {
            new MaterialAlertDialogBuilder(context)
                    .setItems(new String[]{"保存至现有联系人", "新建联系人"}, (dialog, which) -> {
                        if (which == 0)
                            ContactUtils.saveExistContact(context, ContactUtils.getName(result), ContactUtils.getPhoneNum(result));
                        if (which == 1)
                            ContactUtils.createNewContact(context, ContactUtils.getName(result), ContactUtils.getPhoneNum(result));
                    }).show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
        });

        mChipgroup4chip2.setOnClickListener(v -> {
            DabaiUtils.copyText(context, ContactUtils.getName(result));
        });

        mChipgroup4chip3.setOnClickListener(v -> {
            DabaiUtils.copyText(context, ContactUtils.getPhoneNum(result));
        });

        mChipgroup4chip4.setOnClickListener(v -> {

            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + ContactUtils.getPhoneNum(result));
            intent.setData(data);
            startActivity(intent);


        });


        mChipgroup3chip1.setOnClickListener(v -> {
            DabaiUtils.copyText(context, WifiUtils.getSsid(result));
        });

        mChipgroup3chip2.setOnClickListener(v -> {
            DabaiUtils.copyText(context, WifiUtils.getPassword(result));
        });

        mChipgroup3chip3.setOnClickListener(v -> {
            WifiAdmin.linkWifi(context, WifiUtils.getSsid(result), WifiUtils.getSsid(result), WifiUtils.getSsid(result).equals("") ? "" : "wpa");
        });

        //解决滑动冲突
        ViewUtils.FixScrollViewConflict(mResulttext);
        mResulttext.setMovementMethod(ScrollingMovementMethod.getInstance());

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initViews() {
        mToolbar = findViewById(R.id.toolBar);
        mResulttext = findViewById(R.id.resultText);
        mChipgroup1chip1 = findViewById(R.id.chipGroup1Chip1);
        mChipgroup1chip2 = findViewById(R.id.chipGroup1Chip2);
        mChipgroup1chip3 = findViewById(R.id.chipGroup1Chip3);
        mChipgroup1chip4 = findViewById(R.id.chipGroup1Chip4);
        mChipgroup1chip5 = findViewById(R.id.chipGroup1Chip5);
        mChipgroup2chip1 = findViewById(R.id.chipGroup2Chip1);
        mChipgroup2chip2 = findViewById(R.id.chipGroup2Chip2);
        mChipgroup2chip3 = findViewById(R.id.chipGroup2Chip3);
        mChipgroup2chip4 = findViewById(R.id.chipGroup2Chip4);
        mChipgroup3chip1 = findViewById(R.id.chipGroup3Chip1);
        mChipgroup3chip2 = findViewById(R.id.chipGroup3Chip2);
        mChipgroup4chip1 = findViewById(R.id.chipGroup4Chip1);
        mChipgroup4chip2 = findViewById(R.id.chipGroup4Chip2);
        mChipgroup4chip3 = findViewById(R.id.chipGroup4Chip3);
        mChipgroup4chip4 = findViewById(R.id.chipGroup4Chip4);
        mChipgroup3 = findViewById(R.id.chipGroup3);
        mChipgroup4 = findViewById(R.id.chipGroup4);
        mChipgroup3chip3 = findViewById(R.id.chipGroup3Chip3);

    }
}